package com.xuan.shop.controller;

import com.xuan.shop.dto.HttpResp;
import com.xuan.shop.entity.Privs;
import com.xuan.shop.entity.User;
import com.xuan.shop.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/user")
@Api(tags = "用户管理模块")
@CrossOrigin
public class UserController {
    @Autowired
    private IUserService ius;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @PutMapping("/addUser")
    @ApiOperation("添加用户")
    public HttpResp addUser(User user){
        ius.registUser(user);
        return new HttpResp(2001,"用户注册成功",null, LocalDateTime.now());
    }

    @DeleteMapping("/deleteById")
    @ApiOperation("删除用户")
    public HttpResp deleteById(int id){
        ius.deleteById(id);
        return new HttpResp(2002,"用户删除成功",null,LocalDateTime.now());
    }

    @PostMapping("/update")
    @ApiOperation("修改用户")
    public HttpResp update(User user){
        ius.update(user);
        return new HttpResp(2003,"用户修改成功",null,LocalDateTime.now());
    }

    @GetMapping("/findAll")
    @ApiOperation("查询用户")
    public HttpResp findAll(){
        return new HttpResp(2001,"用户查询成功",ius.findAll(),LocalDateTime.now());
    }

    @GetMapping("/login")
    @ApiOperation("用户登录检测")
    public HttpResp login(String username,String password){
        User user=ius.login(username, password);
        List<Privs> ps=user.getPrivs();
        redisTemplate.opsForValue().set(username,ps);
        return new HttpResp(3001,"登录成功",username,LocalDateTime.now());
    }
}
